package loader
{
	import mx.core.Application;
	import mx.events.ModuleEvent;
	import mx.modules.IModuleInfo;
	import mx.modules.ModuleManager;
	import net.URI;
	
	public class ModuleLoader extends AbstractLoader
	{
		
		public var moduleInfo:IModuleInfo;
		
	
		
		public function ModuleLoader()
		{
			super();
		}
		
		public override function startLoad( url:String, desc:String, onProgress:Function, onCompleted:Function, onError:Function = null ):void
		{
			url = URI.moduleURI( url );
			
			super.startLoad( url, desc, onProgress, onCompleted, onError );
			
			moduleInfo =  ModuleManager.getModule( url ); 
			
			moduleInfo.addEventListener( ModuleEvent.READY, completed );
			moduleInfo.addEventListener( ModuleEvent.PROGRESS, progress );
			moduleInfo.addEventListener( ModuleEvent.ERROR, error );
			
			moduleInfo.load();
		}
		
		protected function progress( event:ModuleEvent ):void
		{	
			super.onProgress( event.bytesLoaded, event.bytesTotal );
		}
		
		protected function completed( event:ModuleEvent ):void
		{	
			removeListener();
			
			super.onCompleted();
		}
		
		protected function error( event:ModuleEvent ):void
		{	
			removeListener();
			super.onError( event.errorText );
		}
		
		public override function get content():Object
		{
			return moduleInfo.factory.create();
		}
		
		protected function removeListener():void
		{
			moduleInfo.removeEventListener( ModuleEvent.READY, completed );
			moduleInfo.removeEventListener( ModuleEvent.PROGRESS, progress );
			moduleInfo.removeEventListener( ModuleEvent.ERROR, error );
		}
		
	}
}